<?php

if(! function_exists('curl')) {
	function curl($url, $data = null, $header = null, $return_header = false, $cookie_file = ''){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if(! empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		if(is_array($header)){
			if(isset($header['Cookie'])){
				curl_setopt($curl, CURLOPT_COOKIE , $header['Cookie']);
				unset($header['Cookie']);
			}
			if($header) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		}elseif($header === true){
			curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie_file);
			curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie_file);
		}
		if($return_header) curl_setopt($curl, CURLOPT_HEADER, true);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		if($return_header){
			$size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
			$res['header'] = explode(PHP_EOL, substr($output, 0, $size));
			$tmp = explode(' ', $res['header'][0]);
			$res['header']['status'] = $tmp[1];
			$body = substr($output, $size);
			$json = json_decode($body, true);
			$res['body'] = empty($json) ? $body : $json;
		}else{
			$json = json_decode($output, TRUE);
			$res = empty($json) ? $output : $json;
		}
		curl_close($curl);
		return $res;
	}

	if (!function_exists('encode')) {
		function encode($data, $code = 200, $status = 'success', $message = 'ok')
		{
			$res = [
				'code'    => $code,
				'status'  => $status,
				'message' => $message,
				'data'    => $data,
			];

			$res = json_encode($res, JSON_UNESCAPED_UNICODE);

			echo $res;

		}
	}

	//分页数据处理
	if(!function_exists('paginateHandle'))
	{
		function paginateHandle($data)
		{
			unset($data['first_page_url'],$data['from'],$data['last_page_url'],$data['links'],$data['next_page_url'],$data['path'],$data['prev_page_url'],$data['to']);

			$row = [
				'list'         => $data['data'],
				'current_page' => $data['current_page'],
				'last_page'    => $data['last_page'],
				'per_page'     => $data['per_page'],
				'total'        => $data['total'],
			];

			return $row;
		}
	}
}
